<template>
  <div id="mining-account" >
    <div style="position: relative"  class="px-30 pb-104">
      <mining-exchange-input :title="$t('从')" v-model="form.volume" :actions="actions"
        @select="onSelect('symbol', $event)" @input="onInput" @max="onMax" :coin="form.symbol"
        :tips="[]" :showMax="true" />
      <div v-if="show" class="font-28 text-grey">{{$t('可用数量')}}：<span class="textColor">{{ amountAvailable }}&nbsp;{{form.symbol.toUpperCase()}}</span>
      </div>
      <div class="flex justify-center my-42" >
        <img src="@/assets/image/assets-center/convert-round.png" alt="" class="w-75 h-75" @click="onSwitch" />
      </div>
      <mining-exchange-input :title="$t('至')" :value="form.volume?(form.volume  * form.rate).toFixed(5):''" :actions="actions"
        @select="onSelect('symbol_to', $event)" :disabled="true" :coin="form.symbol_to"
        :tips="[]" :showMax="false" />
      <div class="exchange-btn w-full flex justify-center mt-116">
        <p class="h-100 btnMain mx-auto flex justify-center items-center w-768"
          @click="onConfirm">
          {{ $t('闪兑') }}
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import MiningExchangeInput from "@/components/mining-exchange-input";
import { Grid, GridItem, Popup, Icon } from "vant";
// import { mapState } from "vuex";
import { _exchangeRage, _getAllWallet, _getBalance, _initWidthdrawl, _widthdrawl, _records } from "@/API/fund.api";
import { _getBalance as __getBalance } from '@/API/trade.api'
import { mapGetters } from "vuex";
import Axios from "@/API/recharge";
import { List,PullRefresh } from 'vant';
import { debounce } from '@/utils/utis'
export default {
  name: "MiningAcccount",
  components: {
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    MiningExchangeInput,
    [List.name]: List,
    [PullRefresh.name]:PullRefresh
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapGetters('user', ['userInfo']),
    amountAvailable() {
      let res
      let data = this.wallets.find(item => item.symbol === this.form.symbol.toLowerCase())
      if (data) {
        res = data.usable 
      } else {
        res = 0
      }
      return res;
    },
    tabList() {
      return [
        { id: 1, text: this.$t('提幣') },
        { id: 2, text: this.$t('交易記錄') }
      ]
    },
    addr() {
      const account = this.userInfo.account
      return account &&  account.substr(0,5) + '********' + account.substr(account.length -5)
    }
  },
  data() {
    return {
        showPopup: false,
        activeRecord: 'exchange',
        valueTwo:0,
        rate: 0,
        form: { // 闪兑
          symbol: 'ETH',
          symbol_to: 'USDT',
          volume: '',
          rate: 0,
          get_volume:''
        },
        interval: null,
        actions: [],
        balance: 0, // 质押余额
        page:1,
        loading: false, // 当loading为true时，转圈圈
        finished: false,  // 数据是否请求结束，结束会先显示'已经全部加载完毕'
        noData:false ,// 如果没有数据，显示暂无数据
        wallets: [] // 钱包列表

    }
  },
  created() {
    _getAllWallet().then(data => {
      console.log('闪兑', data)
      data.extends.map(item => {
        this.actions.push({ symbol: item.symbol, name: item.symbol.toUpperCase() })
      })
      let find_index = this.actions.findIndex(x => x.symbol === 'eth')
      if (find_index > 0 && find_index < this.actions.length) {
        let temp = this.actions[0];
        this.actions[0] = this.actions[find_index];
        this.actions[find_index] = temp;
      }
      this.wallets = data.extends
      this.form.symbol = this.actions[0].name
      let toObj = this.actions.find(item => {
        return item.symbol.toLowerCase() == 'usdt'
      })
      this.form.symbol_to = toObj.name
    })
  },
  methods: {
    onMax() { // 最大
      console.log(this.amountAvailable)
      if (this.amountAvailable / 1) {
        this.form.volume = this.amountAvailable
        this.onInput()
      } else {
        this.$toast(this.$t('你没有可提数量'))
      }
    },
    onInput() { // 获取最新
      this.clearInterval()
      if(this.form.volume==''){
        this.form.get_volume =''
      }else{
        this.debounceFn()
      }
    },
    debounceFn: debounce(function(){
      this.fetchRate(true)
    },300),
    fetchRate(callback) { // interval
      _exchangeRage(this.form).then(data => {
          const { get_rate, get_volume } = data
          this.form.rate = get_rate
          this.form.get_volume = get_volume
          this.clearInterval()
          if (callback && typeof callback === 'function') {
            callback()
          }
        })
    },
    onSwitch() { // 交换
      const temp = this.form.symbol
      this.form.symbol = this.form.symbol_to
      this.form.symbol_to = temp
      this.form.volume = ''
      this.clearInterval()
    },
    onSelect(type, evt) { // 选择
      this.form[type] = evt.name
      if (this.form.symbol !== this.form.symbol_to) {
        this.form.volume = ''
      }
      this.clearInterval()
    },
    onConfirm() { // 闪兑
      this.clearInterval()
      if (this.form.volume == '') {
        this.$toast(this.$t('请输入数量'));
      } else {
        this.fetchRate(() => {
          this.$emit("exchange", this.form);
        })
      }
    },
    clearInterval() { // 清除定时器
      clearInterval(this.interval)
      this.interval = null
    }
  },
  beforeDestroy() {
    // console.log('beforeDestroy')
    this.clearInterval()
  }
};
</script>

<style scoped lang="sass">
.exchange-btn
  bottom: 48px
  left: 0
  font-size: 35px
  p
    border-radius: 10px
.active
    color: #000
    &:after
        content: ''
        display: block
        width: 140px
        height: 8px
        background: #2D78F9
        margin: 0 auto
        position: absolute
        bottom: 0
</style>
